<template>
  <div class="goods-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索信件ID/发送人/内容"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增信件
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredMessages" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="messageId" label="信件ID" width="130" sortable align="center" />
      <el-table-column prop="sender" label="发送人" width="150" />
      <el-table-column prop="receiver" label="接收人" width="120" />
      <el-table-column prop="sendMethod" label="发送方式" width="120">
        <template #default="{ row }">
          <el-tag effect="plain" :type="methodTagType[row.sendMethod]">
            {{ row.sendMethod }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="信件状态" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="statusTagType[row.status]" effect="light">
            {{ statusMap[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sendDate" label="发送时间" width="140" sortable />
      <el-table-column prop="content" label="信件内容" width="220">
        <template #default="{ row }">
          <div class="content-preview">{{ row.content }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.messageId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑信件信息' : '新增表白信件'"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="信件ID" prop="messageId">
          <el-input 
            v-model="formData.messageId" 
            :disabled="isEditMode"
            placeholder="请输入信件ID（如：MSG2024001）"
          />
        </el-form-item>
        <el-form-item label="发送人" prop="sender">
          <el-input 
            v-model="formData.sender"
            placeholder="请输入发送人昵称"
          />
        </el-form-item>
        <el-form-item label="接收人" prop="receiver">
          <el-input 
            v-model="formData.receiver"
            placeholder="请输入接收人姓名"
          />
        </el-form-item>
        <el-form-item label="发送方式" prop="sendMethod">
          <el-select 
            v-model="formData.sendMethod"
            placeholder="请选择发送方式"
            style="width: 100%"
          >
            <el-option
              v-for="item in sendMethods"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="信件状态" prop="status">
          <el-select 
            v-model="formData.status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发送时间" prop="sendDate">
          <el-date-picker
            v-model="formData.sendDate"
            type="datetime"
            placeholder="选择发送时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="信件内容" prop="content">
          <el-input 
            type="textarea"
            v-model="formData.content" 
            rows="4"
            placeholder="请输入表白内容（支持emoji）"
            show-word-limit
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 发送方式配置
const sendMethods = [
  '文字墙',
  '语音',
  '视频',
  '礼物',
  '线下'
]

// 状态配置
const statusList = [
  { value: 0, label: '待审核' },
  { value: 1, label: '已公开' },
  { value: 2, label: '匿名展示' }
]

// 标签样式映射
const methodTagType = {
  '文字墙': 'info',
  '语音': 'warning',
  '视频': 'danger',
  '礼物': 'success',
  '线下': 'primary'
}

const statusTagType = {
  0: '',
  1: 'success',
  2: 'warning'
}

const statusMap = {
  0: '待审核',
  1: '已公开',
  2: '匿名'
}

// 信件数据（10条）
const messagesList = ref([
  {
    messageId: 'MSG2024001',
    sender: '匿名小熊猫',
    receiver: '林同学',
    sendMethod: '文字墙',
    status: 1,
    sendDate: '2024-05-20 09:30:00',
    content: '从第一次在图书馆相遇，你的侧脸就刻在了我心里。希望你考研顺利，我会一直默默支持你！💖'
  },
  {
    messageId: 'MSG2024002',
    sender: '机电小王',
    receiver: '钱同学',
    sendMethod: '视频',
    status: 2,
    sendDate: '2024-05-19 18:45:00',
    content: '你打篮球的样子太帅了！虽然不敢当面说，但想让你知道有个小迷妹一直在关注你🏀'
  },
  {
    messageId: 'MSG2024003',
    sender: '经管院学姐',
    receiver: '张学弟',
    sendMethod: '语音',
    status: 0,
    sendDate: '2024-05-20 14:20:00',
    content: '毕业在即，不想留下遗憾。这三年你带给我太多温暖，希望未来还能相遇❤️'
  },
  {
    messageId: 'MSG2024004',
    sender: '暗恋者9527',
    receiver: '曹同学',
    sendMethod: '礼物',
    status: 1,
    sendDate: '2024-05-18 12:00:00',
    content: '偷偷放在你桌上的玫瑰花和手写信，希望你能感受到我的心意🌹'
  },
  {
    messageId: 'MSG2024005',
    sender: '匿名',
    receiver: '朱班长',
    sendMethod: '文字墙',
    status: 2,
    sendDate: '2024-05-19 21:15:00',
    content: '认真负责的你特别有魅力！每次班会都忍不住多看你几眼👀'
  },
  {
    messageId: 'MSG2024006',
    sender: '吉他少年',
    receiver: '音乐社学姐',
    sendMethod: '线下',
    status: 1,
    sendDate: '2024-05-20 10:05:00',
    content: '去年迎新晚会的合奏是我最珍贵的回忆，期待再次同台演出🎸'
  },
  {
    messageId: 'MSG2024007',
    sender: '实验搭档',
    receiver: '李同学',
    sendMethod: '文字墙',
    status: 1,
    sendDate: '2024-05-17 16:30:00',
    content: '一起做课题的三个月，你的严谨认真让我钦佩，能继续组队学习吗？🔬'
  },
  {
    messageId: 'MSG2024008',
    sender: '图书馆常客',
    receiver: '窗边女孩',
    sendMethod: '匿名',
    status: 2,
    sendDate: '2024-05-20 08:00:00',
    content: '每天9点靠窗第三位的你，专注的样子很美📚 今天终于鼓起勇气留言'
  },
  {
    messageId: 'MSG2024009',
    sender: '田径队新人',
    receiver: '陈教练',
    sendMethod: '文字墙',
    status: 1,
    sendDate: '2024-05-19 20:00:00',
    content: '谢谢您每次加训的陪伴！您的鼓励是我坚持的动力🏃♀️'
  },
  {
    messageId: 'MSG2024010',
    sender: '毕业学长',
    receiver: '全体学弟妹',
    sendMethod: '视频',
    status: 1,
    sendDate: '2024-05-20 22:00:00',
    content: '最后一天值班，想把所有未说出口的感谢和祝福都留给这个温暖的地方🎓'
  }
])

// 搜索功能
const searchText = ref('')
const filteredMessages = computed(() => {
  const search = searchText.value.toLowerCase()
  return messagesList.value.filter(msg => 
    msg.messageId.toLowerCase().includes(search) ||
    msg.sender.toLowerCase().includes(search) ||
    msg.content.toLowerCase().includes(search)
  )
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
  messageId: '',
  sender: '匿名',
  receiver: '',
  sendMethod: '文字墙',
  status: 0,
  sendDate: new Date().toISOString().split('T')[0],
  content: ''
})

// 表单验证规则
const formRules = {
  messageId: [
    { required: true, message: '信件ID不能为空', trigger: 'blur' },
    { pattern: /^MSG\d{7}$/, message: '格式：MSG+7位数字', trigger: 'blur' }
  ],
  sender: [
    { required: true, message: '请输入发送人', trigger: 'blur' },
    { min: 2, max: 20, message: '长度2-20个字符', trigger: 'blur' }
  ],
  content: { required: true, message: '请输入表白内容', trigger: 'blur' }
}

// 处理添加
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (messageId) => {
  ElMessageBox.confirm('确定要永久删除此信件？', '警告', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger'
  }).then(() => {
    messagesList.value = messagesList.value.filter(m => m.messageId !== messageId)
    ElMessage.success('信件删除成功')
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = messagesList.value.findIndex(m => m.messageId === formData.messageId)
    messagesList.value.splice(index, 1, { ...formData })
  } else {
    if (messagesList.value.some(m => m.messageId === formData.messageId)) {
      return ElMessage.warning('信件ID已存在')
    }
    messagesList.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '更新成功' : '信件已提交审核')
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    messageId: '',
    sender: '匿名',
    receiver: '',
    sendMethod: '文字墙',
    status: 0,
    sendDate: new Date().toISOString().split('T')[0],
    content: ''
  })
}
</script>

<style scoped lang="scss">
.goods-management {
  padding: 24px;
  background: #fff5f7;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(214,51,132,0.08);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  :deep(.table-header) th {
    background-color: #fff5f7 !important;
    color: #d63384;
    font-weight: 600;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(214,51,132,0.08);
  }

  .el-tag {
    font-size: 13px;
    padding: 0 8px;
    height: 26px;
    line-height: 24px;
  }

  .content-preview {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height: 1.5;
    color: #6b1b7a;
  }
}

.el-dialog {
  border-radius: 12px;
  
  .el-dialog__header {
    border-bottom: 1px solid #ffd6e6;
    margin: 0 24px;
    padding: 24px 0 16px;
  }
  
  .el-dialog__body {
    padding: 24px 32px;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #ffd6e6;
    padding: 16px 24px;
  }
}

.el-form-item {
  margin-bottom: 20px;
}
</style>